﻿using System;
using System.Collections.Generic;
using System.Data.Common;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xproject.Framework.Core;
using Xproject.Framework.Core.DataContext;
using Xproject.Framework.Core.Repositories;
using Model.WeiXin;
using Repository.WeiXinProject;
using Xproject.Util;
using Repository.Util;
using Model.Util;
using Services.ZXBuiness;
using Model.WXshopBuiness;

namespace Services.WeiXinProject
{
    public class UserInfoServices : Service
    {
        IRepositoryAsync<WeiXinUser> m_WeiXinUserRepository;
        IRepositoryAsync<UploadFile> m_UploadFileRepository;
        IRepositoryAsync<Identity> m_IdentityRepository;
        ZXUserInfoServives m_ZXUserInfoServives;
        public UserInfoServices(IDataContextAsync dataContext, ZXUserInfoServives mZXUserInfoServives) : base(dataContext)
        {
            m_WeiXinUserRepository = m_UnitOfWork.RepositoryAsync<WeiXinUser>();
            m_UploadFileRepository = m_UnitOfWork.RepositoryAsync<UploadFile>();
            m_IdentityRepository = m_UnitOfWork.RepositoryAsync<Identity>();
            m_ZXUserInfoServives = mZXUserInfoServives;
        }

        public string CreateUserCode(string userId)
        {
            Identity iden = new Identity();
            iden.CreateTime = DateTime.Now;
            iden.EntityState = EntityState.Added;
            iden.ProjectID = userId;
            iden.Guid = Guid.NewGuid().ToString();
            m_IdentityRepository.Insert(iden);
            m_UnitOfWork.SaveChanges();
            Identity nid = m_IdentityRepository.Get(iden.Guid);

            return nid.ID.ToString();
        }

        public WeiXinUser GetById(string userId)
        {
            return m_WeiXinUserRepository.Get(userId);
        }

        public WeiXinUser GetWeiXinUserByOpenId(string openId)
        {
            return m_WeiXinUserRepository.GetByOpenId(openId);
        }
        /// <summary>
        /// 通过openid 获得带有直销信息的用户模型 
        /// 直销信息可以不存在
        /// </summary>
        /// <param name="openId"></param>
        /// <returns></returns>
        public ZXUserInfoModel GetWeiXinZXUserInfoByOpenId(string openId)
        {
            return m_WeiXinUserRepository.GetZXUserInfoByOpenId(openId);
        }

        public WeiXinUser GetWeiXinUserByCode(string userCode, string password)
        {
            if (string.IsNullOrEmpty(userCode) || string.IsNullOrEmpty(password))
            {
                return null;
            }
            return m_WeiXinUserRepository.GetByUserCode(userCode, password);
        }

        public ZXUserInfoModel GetWeiXinZXUserInfoByCode(string userCode, string password)
        {
            if (string.IsNullOrEmpty(userCode) || string.IsNullOrEmpty(password))
            {
                return null;
            }
            return m_WeiXinUserRepository.GetZXUserInfoByUserCode(userCode, password);
        }

        public List<WeiXinUser> GetWeiXinUserList(string site,int offset, int limit, string nickName, string userCode, string mobile, int state, DateTime? startTime, DateTime? endTime, string order, string ordername, out int   total)
        {
            total = 0;
             List<WeiXinUser> users =  m_WeiXinUserRepository.GetWXUserList(site, nickName, userCode, mobile, state, startTime, endTime, order, ordername);
            total = users.Count;
            return users.Skip(offset).Take(limit).ToList();             
        }

        /// <summary>
        /// 变更用户信息
        /// </summary>
        /// <param name="userInfo"></param>
        /// <param name="focused"></param>
        /// <param name="focusTime"></param>
        /// <returns></returns>
        public bool UpdateWeiXinUserInfo(WeiXinUser userInfo)
        {            
            userInfo.EntityState = EntityState.Modified;
            m_WeiXinUserRepository.Update(userInfo);
            return m_UnitOfWork.SaveChanges() == 1;
        }
        /// <summary>
        /// 新增一个微信用户记录
        /// </summary>
        /// <param name="nickName"></param>
        /// <param name="openId"></param>
        /// <param name="headUrl"></param>
        /// <param name="area"></param>
        /// <param name="sex"></param>
        /// <param name="unionId"></param>
        /// <param name="parentId"></param>
        ///  <param name="zxUserType">默认都是0初级用户</param>
        /// 
        /// <returns></returns>
        public WeiXinUser InsertWeiXinUserInfo(string nickName, string openId, string headUrl, string area, string sex, string unionId, string parentId)
        {
            if (string.IsNullOrEmpty(openId))
            {
                return null;
            }
            try
            {
                WeiXinUser user = new WeiXinUser();
                user.UserID = Guid.NewGuid().ToString();
                user.NickName = nickName;
                user.OpenId = openId;
                user.HeadUrl = headUrl;
                user.Area = area;
                user.Sex = sex;
                user.UnionId = unionId;
                user.ParentID = parentId;
                user.IsFocus = 1;
                user.LastLoginTime = user.CreateTime = user.FocusTime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                user.EntityState = EntityState.Added;
                user.UserCode = CreateUserCode(user.UserID);
                user.Password = CommonHelper.MD5(user.UserCode + "chenqiang"); //初次默认使用 usercode +chenqiang 当密码

                m_WeiXinUserRepository.Insert(user);
                if (m_UnitOfWork.SaveChanges() == 1)
                {
                    return user;
                }
            }
            catch (Exception ex)
            {
                LogHelper.WriteErrorLog("关注注册失败 "+ex.Message.ToString(), ex);
            }
            return null;
        }

        public WeiXinUser InserWeiXinUserInfo_ZX(string nickName, string openId, string headUrl, string area, string sex, string unionId, string parentId,
            long? zxparentId,int? zxUserSource,string zxPlatform,int? zxLevel,int zxUserType,int IsFocus,long jifeng)
        {
            if (string.IsNullOrEmpty(openId))
            {
                return null;
            }
            try
            {
                m_UnitOfWork.BeginTransaction();
                WeiXinUser user = new WeiXinUser();
                user.UserID = Guid.NewGuid().ToString();
                user.NickName = nickName;
                user.OpenId = openId;
                user.HeadUrl = headUrl;
                user.Area = area;
                user.Sex = sex;
                user.UnionId = unionId;
                user.ParentID = parentId;
                user.IsFocus = IsFocus;
                user.LastLoginTime = user.CreateTime = user.FocusTime = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                user.EntityState = EntityState.Added;
                user.UserCode = CreateUserCode(user.UserID);
                user.Password = CommonHelper.MD5(user.UserCode + "chenqiang"); //初次默认使用 usercode +chenqiang 当密码
                m_WeiXinUserRepository.Insert(user);
                m_ZXUserInfoServives.RegisterZXUserContent(user.UserID, user.NickName, zxparentId, zxUserSource, zxPlatform, zxLevel, zxUserType, jifeng);

                if (m_UnitOfWork.SaveChanges() == 2)
                {
                    m_UnitOfWork.Commit();
                    return user;
                }
                else
                {
                    m_UnitOfWork.Rollback();
                }
            }
            catch (Exception ex)
            {
                m_UnitOfWork.Rollback();
                LogHelper.WriteErrorLog("关注注册失败 " + ex.Message.ToString(), ex);
            }
            return null;
          
        }

        /// <summary>
        /// 添加用户  一般（机器人）
        /// </summary>
        /// <param name="user"></param>
        /// <param name="uf"></param>
        /// <returns></returns>
        public bool AddWeiXinUser(WeiXinUser user,UploadFile uf)
        {
            int result = 0;
            m_UnitOfWork.BeginTransaction();
            if (user != null)
            {              
                user.CreateTime = DateTime.Now;
                user.EntityState = EntityState.Added;
                user.FocusTime = DateTime.Now;
                user.LastLoginTime = DateTime.Now;
                user.UserCode = "Robot-" + CreateUserCode(user.UserID);
                m_WeiXinUserRepository.Insert(user);
                result++;
            }
            if (uf != null)
            {
                uf.CreateTime = DateTime.Now;
                uf.EntityState = EntityState.Added;
                m_UploadFileRepository.Insert(uf);
                result++;
            }
            if (m_UnitOfWork.SaveChanges() == result)
            {
                m_UnitOfWork.Commit();
                return true;
            }
            else
            {
                m_UnitOfWork.Rollback();
                return false;
            }           
        }

        /// <summary>
        /// 编辑用户  一般（机器人）
        /// </summary>
        /// <param name="user"></param>
        /// <param name="uf"></param>
        /// <returns></returns>
        public bool EditWeiXinUser(WeiXinUser user, UploadFile uf)
        {
            int result = 0;
            m_UnitOfWork.BeginTransaction();
            if (user != null)
            {                
                user.EntityState = EntityState.Modified;                 
                user.LastLoginTime = DateTime.Now;
                m_WeiXinUserRepository.Update(user);
                result++;
            }
            if (uf != null)
            {
                uf.CreateTime = DateTime.Now;
                uf.EntityState = EntityState.Added;
                m_UploadFileRepository.Insert(uf);
                result++;
            }
            if (m_UnitOfWork.SaveChanges() == result)
            {
                m_UnitOfWork.Commit();
                return true;
            }
            else
            {
                m_UnitOfWork.Rollback();
                return false;
            }
        }

        /// <summary>
        /// 变更用户关注或者不关注
        /// </summary>
        /// <param name="userId"></param>
        /// <param name="openId"></param>
        /// <param name="subscribe"></param>
        /// <returns></returns>
        public bool UpdateUserSubscribeState(string userId, string openId, int subscribe = 1)
        {
            WeiXinUser u = m_WeiXinUserRepository.GetByOpenId(openId);
            if (u != null)
            {
                u.IsFocus = subscribe;
                if (u.IsFocus == 1) u.FocusTime = DateTime.Now;
                else
                    u.CancelTime = DateTime.Now;
                u.EntityState = EntityState.Modified;
                m_WeiXinUserRepository.Update(u);
                return m_UnitOfWork.SaveChanges() == 1;
            }
            return true;
        }
    }
}
